package com.baidu.manager.common.shiro;

import com.baidu.manager.common.exception.JqlException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @Author: jql
 * @description: TODO(生成Token)
 * @Date: Created by 14:22 2018/4/20
 */
public class TokenGenerator {

    private static final char[] hexCode = "0123456789abcdef".toCharArray();
    public static String generateValue(){
        return generateValue(UUID.randomUUID().toString());
    }

    public static String generateValue(String param){
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(param.getBytes());
            byte[] messageDigest = algorithm.digest();
            return toHexString(messageDigest);
        } catch (NoSuchAlgorithmException e) {
            throw new JqlException("生成token失败",e);
        }
    }

    public static String toHexString(byte[] data){
        if(data == null){
            return null;
        }
        StringBuilder r = new StringBuilder(data.length*2);
        for (byte b:data){
            r.append(hexCode[(b >> 4) & 0xF]);
            r.append(hexCode[(b & 0xF)]);
        }
        return r.toString();
    }
}
